package wangjg.mda.lang;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

public class LineUtil {
	public static final int MODE_CHAR = 1;
	public static final int MODE_STRING = 2;
	
	private int mode;
	private List<Integer> lineRecord = new ArrayList<Integer>();
	
	public void parse(char[] cbuf){
		this.mode = MODE_CHAR;
		for(int i=0; i< cbuf.length; i++){
			char ch = cbuf[i];
			if(ch=='\r'){
				lineRecord.add(i);
				continue;
			}
			if(ch=='\n'){
				if(i==0){
					lineRecord.add(i);
					continue;
				}else{
					if(cbuf[i-1]=='\r'){
						lineRecord.set(lineRecord.size()-1, i);
					}else{
						lineRecord.add(i);
					}
					continue;
				}
			}
		}
	}
	
	public void parse(Reader reader){
		this.mode = MODE_STRING;
		try {
			BufferedReader br = new BufferedReader(reader);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while((line=br.readLine())!=null){
				sb.append(line);
				sb.append('\n');
				lineRecord.add(sb.length());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
		}
	}
	
	public int getLineNo(int pos){
		for(int i=0;i<lineRecord.size();i++){
			if(lineRecord.get(i)>pos){
				return i+1;
			}
		}
		return -1;
	}

	public int getMode() {
		return mode;
	}

	public void setMode(int mode) {
		this.mode = mode;
	}
}
